//
//  JPTool.m
//  JPProjectConfigureDemo
//
//  Created by Carpenter on 2018/3/6.
//  Copyright © 2018年 carpenter. All rights reserved.
//

#import "JPTool.h"


@implementation JPTool

+(void)changeWindowRootViewController:(UIViewController*)controller{
    
    CATransition *animation = [CATransition animation];
    animation.duration = 1.2;
    animation.type = @"rippleEffect";
    animation.subtype = kCATransitionFromTop;
    
    [[UIApplication sharedApplication].delegate.window.layer addAnimation:animation forKey:@""];
    [[UIApplication sharedApplication].delegate.window setRootViewController:controller];
    
}
+(void)callPhone:(NSString *)mobile{
    
    if ([JPTool isBlank:mobile]) return;
    
    NSString * tele = [NSString stringWithFormat:@"telprompt:%@",mobile];
    
    NSURL * url = [NSURL URLWithString:tele];
    
    /// 解决iOS10及其以上系统弹出拨号框延迟的问题
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 11.0, *)) {
            /// 10及其以上系统
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
            /// 10以下系统
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    
}
+(CGFloat)newFontSize:(CGFloat)fontSize{
    if ([UIScreen mainScreen].bounds.size.width < 375) {
        fontSize = fontSize - 1;
    }else if ([UIScreen mainScreen].bounds.size.width > 375){
        fontSize = fontSize + 1;
    }
    return fontSize;
}



+(NSString *)convertJsonToString:(NSDictionary *)dict{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

+(NSDictionary *)convertStringToJson:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err){
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


+ (void) cuttingRectWithOriginalRect:(CGRect)rect direction:(JPRectCuttingStartDirection)direction amount:(CGFloat)amount completionBlock:(CuttingFinishBlock)completionBlock{
    
    CGRect rect1;
    CGRect rect2;
    
    CGRectEdge edge;
    switch (direction) {
        case JPRectCuttingStartDirectionLeftToRight:
            edge = CGRectMinXEdge;
            break;
        case JPRectCuttingStartDirectionRightToLeft:
            edge = CGRectMaxXEdge;
            break;
        case JPRectCuttingStartDirectionTopToBottom:
            edge = CGRectMinYEdge;
            break;
        case JPRectCuttingStartDirectionBottomToTop:
            edge = CGRectMaxYEdge;
            break;
        default:
            break;
    }
    
    CGRectDivide(rect, &rect1, &rect2, amount, edge);
    
    if (completionBlock) {
        completionBlock(rect1,rect2);
    }
    
}
 

@end
 

@implementation JPTool (Accout)

NSString * const kToolAccoutLocalDataKey = @"Tool_Accout_data_key";

+(BOOL)isLogining{
    
    return [[NSUserDefaults standardUserDefaults] objectForKey:kToolAccoutLocalDataKey] == nil ? false : true;
}

+(void)logingout{
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kToolAccoutLocalDataKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(id)accoutData{
    
    return [[NSUserDefaults standardUserDefaults] objectForKey:kToolAccoutLocalDataKey];
}

+(BOOL)synchronizeStorageAccoutData:(id)data{
    if([self isBlank:data]) return false;
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:kToolAccoutLocalDataKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return true;
}

@end


NSString * const kTimeStringFormatTypeDefaults = @"yyyy-MM-dd HH:mm:ss";
NSString * const kTimeStringFormatTypeChinese = @"yyyy年MM月dd日 HH时mm分ss秒";
NSString * const kTimeStringFormatTypeYearMonthDay = @"yyyy/MM/dd";

@implementation JPTool (Time)

+(NSString *)timeStringWithType:(NSString*)timeType interval:(NSTimeInterval)timeInterval{
    NSDateFormatter * formatter = [NSDateFormatter new];
    [formatter setDateFormat:timeType];
    NSString * timeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
    return timeStr;
}

@end

NSString * const kLocalFirstStartKey = @"JPTool_isFirstStart";

@implementation JPTool (Validate)

+(BOOL)isNotchIphone{
    
//    BOOL isIphoneX = ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO);
//    
//    BOOL isIphoneXr = ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) : NO);
//    
//    BOOL isIphoneXs = ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size)  : NO);
//    
//    BOOL isIphoneXs_Max = ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size): NO);
    
    return CGRectGetHeight([UIApplication sharedApplication].statusBarFrame) > 20.0;
}

+(BOOL)isFirstStart{
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:kLocalFirstStartKey]) {
        [[NSUserDefaults standardUserDefaults] setValue:version forKey:kLocalFirstStartKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return true;
    }
    else if (![[[NSUserDefaults standardUserDefaults] objectForKey:kLocalFirstStartKey] isEqualToString:version]){
        [[NSUserDefaults standardUserDefaults] setValue:version forKey:kLocalFirstStartKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return true;
    }
    return false;
    
}

+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

+ (BOOL)isChinese:(NSString *)string {
    
    for(int i=0; i< [string length];i++){
        
        int a = [string characterAtIndex:i];
        
        if( a > 0x4e00 && a < 0x9fff){
            
            return true;
        }
        
    }
    return false;
}

+(BOOL)isMobile:(NSString *)mobile{
    
    if(mobile.length <= 0) return false;
    
    NSString *pattern = @"^(0|86|17951)?(13[0-9]|15[012356789]|16[0-9]|17[678]|18[0-9]|19[0-9]|14[57])[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:mobile];
    return isMatch;
    
}
+ (BOOL)isQualifiedPsw:(NSString *)psw{
    
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:psw];
}

//银行卡正则
+ (BOOL)IsBankCard:(NSString *)cardNumber

{
    
    for (int i=0; i<cardNumber.length; i++) {
        
        NSString *c=[NSString stringWithFormat:@"%c",[cardNumber characterAtIndex:i]];
        
        if(![c isEqualToString:@"0"]&&![c isEqualToString:@"1"]&&![c isEqualToString:@"2"]&&![c isEqualToString:@"3"]&&![c isEqualToString:@"4"]&&![c isEqualToString:@"5"]&&![c isEqualToString:@"6"]&&![c isEqualToString:@"7"]&&![c isEqualToString:@"8"]&&![c isEqualToString:@"9"]){
            
            return NO;
            
        }
        
    }
    
    if(cardNumber.length==0){
        return NO;
    }
    
    NSString *digitsOnly =@"";
    
    char c;
    
    for (int i = 0; i < cardNumber.length; i++){
        
        c = [cardNumber characterAtIndex:i];
        
        if (isdigit(c)){
            
            digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
        }
        
    }
    
    int sum = 0;
    
    int digit = 0;
    
    int addend = 0;
    
    BOOL timesTwo =false;
    
    for (NSInteger i = digitsOnly.length - 1; i >= 0; i--) {
        
        digit = [digitsOnly characterAtIndex:i] - '0';
        
        if (timesTwo){
            
            addend = digit * 2;
            
            if (addend > 9) {
                
                addend -= 9;
            }
            
        }else {
            
            addend = digit;
            
        }
        
        sum += addend;
        
        timesTwo = !timesTwo;
    }
    
    int modulus = sum % 10;
    
    return modulus == 0;
    
}



+ (BOOL)isIDCard:(NSString *)ID {
    NSString * reg = @"(^[1-6][0-7][\\d]{4}((19[\\d]{2})|(20[0-1][\\d]))((0[1-9])|(1[0-2]))((0[1-9])|([1-2]\\d)|(3[0-1]))[\\d]{3}[\\dxX]$)";
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    
    if (![predicate evaluateWithObject:ID])  return false;
    
    NSMutableArray *ids = [NSMutableArray arrayWithCapacity:18];
    for (int i = 0; i < ID.length; i++) {
        NSString *str = [ID substringWithRange:NSMakeRange(i, 1)];
        [ids addObject:str];
    }
    NSArray *modulus = @[@7,@9,@10,@5,@8,@4,@2,@1,@6,@3,@7,@9,@10,@5,@8,@4,@2];
    NSArray *matchLst = @[@1,@0,@10,@9,@8,@7,@6,@5,@4,@3,@2];
    NSInteger sum = 0;
    for (int i = 0; i < modulus.count; i++) {
        sum += ([modulus[i] integerValue] * [ids[i] integerValue]);
    };
    NSInteger check = [matchLst[sum%11] integerValue];
    
    if ([[ids.lastObject uppercaseString] isEqualToString:@"X"]) {
        
        if (check != 10) return false;
        
    }else{
        
        if ([ids.lastObject integerValue] != check) return false;
    }
    return true;
}
+ (BOOL)isBlank:(id)sender{
    
    if (sender == nil || sender == NULL || [sender isKindOfClass:[NSNull class]]) return true;
    
    if([sender respondsToSelector:@selector(length)]){
        return [sender length] == 0;
    }
    //    if///////// ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) return true;
    
    return false;
}
+ (BOOL)isInputText:(NSString *)numString shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string length:(NSInteger)stringLenght{
    if (string.length == 0){
        return YES;
    }
    NSInteger existedLength = numString.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    if (existedLength - selectedLength + replaceLength > stringLenght) {
        return NO;
    }
    return YES;
}

@end
